package com.tangtang.basic.threads;

import java.util.concurrent.locks.ReentrantLock;

public class Demo3AQS {
    private int i = 0;

    public static void main(String[] args) {
        Demo3AQS demo1 = new Demo3AQS();

      new Thread(  new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <10 ; i++) {
                    demo1.add();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(  new Runnable() {
            @Override
            public void run() {

                for (int i = 0; i <10 ; i++) {
                    demo1.add();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

    public   void add(){
        ReentrantLock reentrantLock = new ReentrantLock();
        boolean tryLock = reentrantLock.tryLock();
        if(tryLock){
            reentrantLock.lock();

            try {
                i++;
                System.out.println(Thread.currentThread().getName()+"->"+i+":state->"+reentrantLock.isLocked());
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                reentrantLock.unlock();
            }
        }


    }


}
